import React, { useCallback } from "react";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import dayjs from "dayjs";
import { Button } from "@/components/ui/button";
import { Loading } from "@/components/ui/loading";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { ArrowUpDown, CalendarIcon } from "lucide-react";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import {
  RootStateI,
  VbpBatchI,
  VbpDeptDutyI,
  VbpDeptDutyStatsI,
} from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import {
  createVbpDeptDuty,
  updateVbpDeptDuty,
  searchVbpDeptDutyList,
  searchVbpDeptDutyStats,
  deleteVbpDeptDuty,
  exportVbpDeptDutyStats,
} from "@/api";
import { useSearchParams, Link } from "react-router-dom";
import request from "@/api/http_class";
import { hasPermission } from "@/lib/utils";
import { useSelector } from "react-redux";

const formSchema = z.object({
  id: z.string().optional(),
  vbpBatchId: z.string({ required_error: "请先选择集采批次药品" }),
  deptYbName: z.string({ required_error: "请选择科室" }),
  pinyin: z.string().optional(),
  py: z.string().optional(),
  dutyAmount: z
    .number({ required_error: "请录入任务量" })
    .min(0)
    .max(1000000000000000),
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [vbpDeptDutyList, setVbpDeptDutyList] = React.useState<VbpDeptDutyI[]>(
    []
  );
  const [formData, setFormData] = React.useState<VbpDeptDutyI>();
  const user = useSelector((state: RootStateI) => state.user);
  // const [myDate, setMyDate] = React.useState<Date>();

  const { loading: loadingList, run } = useRequest(
    (paramsString: string) => searchVbpDeptDutyStats(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        // console.log(params);
        setVbpDeptDutyList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(err: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: `${err.detail}`,
        });
      },
    }
  );

  React.useEffect(() => {
    // console.log(searchParams);
    run(searchParams.toString());
  }, [searchParams]);

  const onUpdateClick = (event: any, data: VbpDeptDutyI) => {
    const processedData = Object.assign(
      {},
      defaultValues,
      Object.fromEntries(
        Object.entries(data).reduce((acc, [key, value]) => {
          if (value !== null) {
            acc.push([key, value]);
          }
          return acc;
        }, [] as [string, any][])
      )
    );
    console.log(processedData);
    setTitle("修改信息");
    // 避免将受控组件的值设置成null，否则会有警告，影响未知
    form.reset(processedData);
    setIsDialogOpen(true);
    run(searchParams.toString());
  };

  const onDeleteConfirm = (event: any, data: VbpDeptDutyI) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        deleteVbpDeptDuty(data.id).then(
          (res: any) => {
            // console.log(data);
            // console.log(res);
            toast({
              variant: "success",
              title: "删除成功",
            });
            run(searchParams.toString());
          },
          (err) => {
            toast({
              variant: "destructive",
              title: "删除失败",
              description: `${err.detail}`,
            });
          }
        );
      }
    } catch (err: any) {
      console.log(err);
      toast({
        variant: "success",
        title: "删除失败",
        description: `${err.detail}`,
      });
    } finally {
      setIsSubmitting(false);
      setIsAlertOpen(false);
    }
  };

  const columnHelper = createColumnHelper<VbpDeptDutyStatsI>();
  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <Link
              to={"/medicine/info/" + row.getValue("id")}
              target="_blank"
              rel="noreferrer"
            >
              {row.getValue("id")}
            </Link>
          );
        } else {
          return "ID";
        }
      },
      enableSorting: false,
      enableHiding: false,
    }),
    columnHelper.accessor("vbpBatchId", {
      id: "vbpBatchId",
      header: "集采批次ID",
    }),
    columnHelper.accessor("deptYbName", {
      id: "deptYbName",
      header: "科室名称",
    }),
    columnHelper.accessor("drugname", {
      id: "drugname",
      header: "药品名称",
    }),
    columnHelper.accessor("completedPercent", {
      id: "completedPercent",
      header: "科室已完成比例",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>{`${(row.original.completedPercent * 100).toFixed(
                2
              )}%`}</span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("completed", {
      id: "completed",
      header: "科室已完成量",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>{row.original.completed.toFixed(0)}</span>
              <span>{row.original.miniUnit}</span>
            </div>
          );
        }
      },
    }),
    columnHelper.display({
      id: "rest",
      header: "科室剩余任务量",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>
                {row.original.deptDutyAmount - row.original.completed > 0
                  ? (
                      row.original.deptDutyAmount - row.original.completed
                    ).toFixed(0)
                  : 0}
              </span>
              <span>{row.original.miniUnit}</span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("deptDutyAmount", {
      id: "deptDutyAmount",
      header: "科室任务量",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>{row.original.deptDutyAmount.toFixed(0)}</span>
              <span>{row.original.miniUnit}</span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("hisCode", {
      id: "hisCode",
      header: "HIS代码",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          // console.log(row);
          return row.original.hisCode;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("specification", {
      id: "specification",
      header: "包装规格",
      enableSorting: false,
    }),
    columnHelper.accessor("startDate", {
      id: "startDate",
      header: "批次开始时间",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>{dayjs(row.original.startDate).format("YYYY-MM-DD")}</span>
            </div>
          );
        }
      },
    }),
    columnHelper.accessor("endDate", {
      id: "endDate",
      header: "批次结束时间",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div>
              <span>{dayjs(row.original.endDate).format("YYYY-MM-DD")}</span>
            </div>
          );
        }
      },
    }),
    // 不让临床科室看总任务量
    // columnHelper.accessor("dutyAmount", {
    //   id: "dutyAmount",
    //   header: "医院总任务量",
    //   cell: (props) => {
    //     if (props && props.row) {
    //       const { row } = props;
    //       return (
    //         <div>
    //           <span>{row.original.dutyAmount.toFixed(0)}</span>
    //           <span>{row.original.miniUnit}</span>
    //         </div>
    //       );
    //     }
    //   },
    // }),
    columnHelper.display({
      header: "操作",
      id: "actions",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(event, row.original)}
                loading={isSubmitting}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem
                    onClick={() => onUpdateClick(event, row.original)}
                  >
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  {/* <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                  <Trash className="mr-2 h-4 w-4" /> 删除
                </DropdownMenuItem> */}
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  const defaultValues = {
    id: undefined,
    vbpBatchId: "",
    pinyin: "",
    py: "",
    dutyAmount: 0,
  };

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  const handleFormSubmit = async (data: FormValuesT) => {
    console.log(data);
    try {
      setIsSubmitting(true);
      if (data.id) {
        updateVbpDeptDuty(data).then(
          (res: any) => {
            run(searchParams.toString());
          },
          (err: any) => {
            console.error(err);
          }
        );
      } else {
        createVbpDeptDuty(data).then(
          (res: any) => {
            run(searchParams.toString());
          },
          (err: any) => {
            console.log(err);
          }
        );
      }
      setIsSubmitting(false);
      setIsDialogOpen(false);
      form.reset(defaultValues);
      toast({
        variant: "success",
        title: "数据提交成功",
      });
    } catch (err: any) {
      toast({
        variant: "destructive",
        title: "数据提交失败",
        description: `${err.detail}`,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleUploadSubmit = useCallback((values: any): Promise<any> => {
    console.log(values);
    return new Promise((resolve, reject) => {
      if (values.files.length) {
        const formData = new FormData();
        // 将全部数据转换为FormData格式
        values.files.forEach((item: File) => {
          console.log(item);
          formData.append("files", item);
        });
        console.log(formData);
        request({
          url: `/vbp-dept-duty/import/`,
          method: "POST",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        }).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            toast({
              variant: "success",
              title: "数据导入成功",
              duration: 3000,
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据导入失败",
              description: `${err.detail}`,
              duration: 3000,
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  }, []);

  const handleExportSubmit = useCallback(() => {
    exportVbpDeptDutyStats(location.search.replace(/^\?/, "")).then(
      (res: any) => {
        console.log(res);
        console.log(res.headers["content-type"]);
        const blob = new Blob([res.data], {
          type: res.headers["content-type"],
        });
        // 非IE下载
        if ("download" in document.createElement("a")) {
          const link = document.createElement("a");
          link.style.display = "none";
          // link.href = window.URL.createObjectURL(blob);
          link.href = window.URL.createObjectURL(blob);
          console.log(link.href);
          // 想让浏览器访问到其他相应头，需要在后服务器上设置Access-Control-Expose-Headers。
          // 想要在这里访问到content-disposition中定义的文件名，
          // 需要在后端设置headers.add("Access-Control-Expose-Headers", "Content-Disposition");
          const contentDisposition = res.headers["content-disposition"];
          if (contentDisposition) {
            // console.log(res.headers["content-disposition"]);
            const fileName = window.decodeURI(
              res.headers["content-disposition"].split("=")[1]
            );
            // console.log(fileName);
            link.setAttribute("download", fileName);
          } else {
            link.setAttribute(
              "download",
              `${Math.floor(Date.now() / 1000)}.xlsx`
            );
          }
          document.body.appendChild(link);
          link.click();
          window.URL.revokeObjectURL(link.href); // 释放blob对象
          document.body.removeChild(link);
        } else if (window.navigator && (window.navigator as any).msSaveBlob) {
          // IE10+下载
          const contentDisposition = res.headers.get("content-disposition");
          let fileName = "download.xlsx";
          if (contentDisposition) {
            fileName = decodeURIComponent(contentDisposition.split("=")[1]);
          }
          (window.navigator as any).msSaveBlob(blob, fileName);
        } else {
          console.error("请使用Chrome浏览器");
        }
      },
      (err: any) => {
        console.log(err);
      }
    );
  }, []);

  // const handleExportSubmit = () => {
  //   exportVbpDeptDutyStats(location.search.replace(/^\?/, "")).then(
  //     (res: any) => {
  //       const blob = new Blob([res.data], {
  //         type: res.headers["content-type"],
  //       });
  //       // 非IE下载
  //       if ("download" in document.createElement("a")) {
  //         const link = document.createElement("a");
  //         link.style.display = "none";
  //         // link.href = window.URL.createObjectURL(blob);
  //         link.href = window.URL.createObjectURL(blob);
  //         console.log(link.href);
  //         // 想让浏览器访问到其他相应头，需要在后服务器上设置Access-Control-Expose-Headers。
  //         // 想要在这里访问到content-disposition中定义的文件名，
  //         // 需要在后端设置headers.add("Access-Control-Expose-Headers", "Content-Disposition");
  //         const contentDisposition = res.headers["content-disposition"];
  //         if (contentDisposition) {
  //           // console.log(res.headers["content-disposition"]);
  //           const fileName = window.decodeURI(
  //             res.headers["content-disposition"].split("=")[1]
  //           );
  //           // console.log(fileName);
  //           link.setAttribute("download", fileName);
  //         } else {
  //           link.setAttribute("download", "download.file");
  //         }
  //         document.body.appendChild(link);
  //         link.click();
  //         window.URL.revokeObjectURL(link.href); // 释放blob对象
  //         document.body.removeChild(link);
  //       } else {
  //         // IE10+下载
  //         // navigator.msSaveBlob(blob, fileName);
  //       }
  //     },
  //     (err: any) => {
  //       console.log(err);
  //     }
  //   );
  // };

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading title={`集采科室任务管理`} description="" />
          <Button
            className="p-2 rounded-md hidden"
            onClick={() => {
              form.reset(defaultValues);
              setTitle("创建信息");
              setIsDialogOpen(!isDialogOpen);
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            创建
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          defaultFilterColumn="drugname"
          columns={columns}
          initColumnVisibility={{
            select: false,
            id: false,
            vbpBatchId: false,
          }}
          loading={loadingList}
          data={vbpDeptDutyList}
          totalCount={totalCount}
          showImportButton={true}
          showExportButton={hasPermission(
            user,
            "export_vbp_dept_duty_sql",
            "{'POST'}"
          )}
          onSubmitFiles={handleUploadSubmit}
          onExportSubmit={handleExportSubmit}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent className="max-w-3xl h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle></DialogTitle>
              <DialogDescription></DialogDescription>
            </DialogHeader>
            <div className="flex items-center justify-between">
              <Heading title={title} description={description} />
            </div>
            <Separator />
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(handleFormSubmit)}
                className="w-full space-y-8"
              >
                <div className="flex flex-col gap-4">
                  {formData && formData.id ? (
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={formData && formData.id ? true : false}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  ) : (
                    <></>
                  )}
                  <FormField
                    control={form.control}
                    name="vbpBatchId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>集采批次药品</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="集采批次药品"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="deptYbName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>科室名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={true}
                            placeholder="科室名称"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="dutyAmount"
                    // render={({ field }) => (
                    render={({ field: { onChange, value } }) => (
                      <FormItem>
                        <FormLabel>任务量</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            disabled={isSubmitting}
                            placeholder="任务量"
                            // {...field}
                            onChange={(e) => onChange(e.target.valueAsNumber)}
                            value={value}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <Button
                  disabled={isSubmitting}
                  className="ml-auto"
                  type="submit"
                >
                  提交
                </Button>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
